import { Component, OnInit } from '@angular/core';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { Device } from "../../..//entity/device.model";
import { WarmCount } from "../../../entity/turb-early-warn.model";
import { EarlyWarnStatisticeService } from "../../../service/early-warn-statistice.service";
import { ApplicationService } from '../../../service/application.service';
@Component({
  selector: 'app-early-warn-statistics',
  templateUrl: './early-warn-statistics.component.html',
  styleUrls: ['./early-warn-statistics.component.css']
})
export class EarlyWarnStatisticsComponent implements OnInit {
  public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine, DeviceCategoryEnum.inverter];
  public devices: Device[] = [];

  /**
	* 风机、测点ids集合
	* 
	* @type @memberof WarnSearchComponent
	*/
  private deviceIds: number[] = [];
  /**
   * 当前选中下标
   * 
   * @type {number}@memberof PowerCompareComponent
   */
  active: number = 0;

  public warmCountFilterData: WarmCount[] = [];

  public currentTime: Date = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 1);

  public weeks: number[] = [1, 2, 3, 4, 5];
  public currentWeek: number;
  public months: number[] = [];
  public currentMonth: number = (new Date().getMonth() + 1);
  public currentYear: number = new Date().getFullYear();

  public endTime = new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate());
  public startTime: Date = new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate() - 1);

  sortF = 'warmWorkTime';
  sortO: number = -1;
  /**
	 * 是否显示进度条
	 */
  isShowBar: boolean = true;
  /**
   * 模糊查询字段
   */
  divDeviceName: string;
  /**
   * 临时的容器（模糊查询中使用）
   */
  temporary: WarmCount[] = [];
  /**
	 *风机最大选择数量
	 *
	 * @type {number}
	 * @memberof EarlyWarnStatisticsComponent
	 */
  public deviceCountLimit: number;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof EarlyWarnStatisticsComponent
   */
  defaultChooseDeviceCount;
  /**
   * 分页中，每页显示的条数
   */
  public pageSize: number;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof EarlyWarnStatisticsComponent
   */
  en: any;
  constructor(
    private earlyWarnStatisticeService: EarlyWarnStatisticeService,
    private application: ApplicationService,
  ) {
  }

  ngOnInit() {
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    if (this.application.currentMenuParams && this.application.currentMenuParams['pageSize']) {
      this.pageSize = Number(this.application.currentMenuParams['pageSize'].paramValue);
    } else {
      this.pageSize = 15;
    }
    for (let j = 1; j < new Date().getMonth() + 2; j++) {
      this.months.push(j)
    }
    this.currentWeek = this.getMonthWeek(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate());
    clearTimeout(timer);
    var timer = setTimeout(() => {
      this.onSearch(this.active);
    }, 500);

    if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
      this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
    } else {
      this.deviceCountLimit = null;
    }
    if (this.application.currentMenuParams && this.application.currentMenuParams['defaultChooseDeviceCount']) {
      this.defaultChooseDeviceCount = Number(this.application.currentMenuParams['defaultChooseDeviceCount'].paramValue);
    } else {
      this.defaultChooseDeviceCount = null;
    }

  }


  onSelectedDevicesChange(ev: Device[]) {

    this.deviceIds = [];
    ev.forEach(o => {
      this.deviceIds.push(o.deviceId);
    })
  }

  public onChangeYear(event) {
    this.currentYear = event;
  }

  public onChangeWeek(event) {
    this.currentWeek = event;
  }

  public onChangeMonth(event) {
    this.currentMonth = event;
  }

  public onClickHeader(n: number) {
    this.active = n;
  }
  onSearch(active) {
    this.isShowBar = true;
    switch (active) {
      case 0:
        //日
        this.startTime = new Date(this.currentTime.getFullYear(), this.currentTime.getMonth(), this.currentTime.getDate());
        this.endTime = new Date(this.currentTime.getFullYear(), this.currentTime.getMonth(), this.currentTime.getDate() + 1);

        break;
      case 1:
        // 周
        //获取指定月份的第一天是周几
        // let week = new Date(this.currentYear, this.currentMonth - 1, 1).getDay();
        // let dayNumber = 7 - week;//第一周的天数
        // if (this.currentWeek == 1) {
        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, 1);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber)
        // } else if (this.currentWeek == 2) {
        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 7)
        // } else if (this.currentWeek == 3) {
        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 7);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 14)
        // } else if (this.currentWeek == 4) {
        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 14);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 21)
        // } else if (this.currentWeek == 4) {
        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 21);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1, 1 + dayNumber + 28);
        // } else if (this.currentWeek == 5) {
        //   let lastDay = this.getLastDay(this.currentYear,this.currentMonth); //最后一天是几号
        //   let lastWeek = new Date(this.currentYear, this.currentMonth - 1, lastDay).getDay();//最后一天是周几     

        //   this.startTime = new Date(this.currentYear, this.currentMonth - 1, lastDay-lastWeek);
        //   this.endTime = new Date(this.currentYear, this.currentMonth - 1,lastDay+1);

        // }
        let week = this.currentTime.getDay();
        week = week == 0 ? 7 : week;
        if (this.currentTime.getDay() == 0) {

        } else {
          this.startTime = new Date(this.currentTime.getFullYear(), this.currentTime.getMonth(), this.currentTime.getDate() - (week - 1));
          this.endTime = new Date(this.currentTime.getFullYear(), this.currentTime.getMonth(), this.currentTime.getDate() + (7 - week) + 1);
        }

        break;
      default:
        this.startTime = new Date(this.currentYear, this.currentMonth - 1);
        this.endTime = new Date(this.currentYear, this.currentMonth);

    }
    this.earlyWarnStatisticeService.getWarnCount(this.deviceIds, this.startTime, this.endTime)
      .then(res => {


        for (let i = 0; i < res.length; i++) {
          res[i].deviceName = res[i].farmName + res[i].deviceName + res[i].tagName;
          //后台返回的warmWorkTime是字符串类型，需要前端进行转换成Number类型。
          res[i].warmWorkTime = Number(res[i].warmWorkTime);
        }



        this.temporary = res;
        this.warmCountFilterData = [...this.temporary];
        this.isShowBar = false;

      })
      .catch(error => {
        console.log('app-early-warn-statistics has error', error);
        this.isShowBar = false;
      })


  }



  //获取本月最后一天
  getLastDay(year, month) {
    var new_year = year;  //取当前的年份   
    var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）   
    if (month > 12)      //如果当前大于12月，则年份转到下一年   
    {
      new_month -= 12;    //月份减   
      new_year++;      //年份增   
    }
    var new_date = new Date(new_year, new_month, 1);        //取当年当月中的第一天   
    return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月最后一天日期   
  }
  //获取今天是本月的第几周
  getMonthWeek(year, month, day) {
    /*
    a = d = 当前日期
    b = 6 - w = 当前周的还有几天过完（不算今天）
    a + b 的和在除以7 就是当天是当前月份的第几周
    */
    var date = new Date(year, parseInt(month) - 1, day), w = date.getDay(), d = date.getDate();
    return Math.ceil(
      (d + 6 - w) / 7
    );
  };


  onKeyup(e) {
    if (this.divDeviceName !== '' && this.divDeviceName) {
      this.divDeviceName.trim(); // 去掉收尾空格
      this.warmCountFilterData = [...this.temporary];
      this.warmCountFilterData = this.warmCountFilterData.filter(o => o.deviceName.indexOf(this.divDeviceName) !== -1);

    } else {
      this.warmCountFilterData = [];
      this.warmCountFilterData = [...this.temporary];
    }
  }

  exportData() {

    // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
    var html = "<html><head><meta charset='utf-8' /></head><body >" + document.getElementById("ex-tab-statistics").outerHTML + "</body></html>";

    // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
    var blob = new Blob([html], { type: "application/vnd.ms-excel" });
    // var a = document.getElementsByTagName("a")[0];
    // 利用URL.createObjectURL()方法为a元素生成blob URL
    var href = URL.createObjectURL(blob);
    document.getElementById("ex").setAttribute("href", href);

    // // 设置文件名，目前只有Chrome和FireFox支持此属性
    document.getElementById("ex").setAttribute("download", "预警统计.xls");
    // a.download = "实际功率曲线.xls";
    // a.click();
    // document.getElementById("ex").click();

  }

}



// WEBPACK FOOTER //
// ./src/app/module/alarm/early-warn-statistics/early-warn-statistics.component.ts